package com.lh.process.engine.annotation;

import com.lh.process.engine.config.ClassPathXmlProcessParser;
import com.lh.process.engine.context.ProcessContextFactory;
import com.lh.process.engine.model.ProcessModel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.context.annotation.ImportBeanDefinitionRegistrar;
import org.springframework.core.type.AnnotationMetadata;

import java.util.List;

/**
 * 获取启动EnableProcessEngine的配置文件，并将其实例通过spring实例化
 * @author: linghao
 * @since: 2022/10/25
 */
@Slf4j
public class ProcessRegister implements ImportBeanDefinitionRegistrar {

    @Override
    public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry) {
       try {
           String processFile = (String) importingClassMetadata.getAnnotationAttributes(EnableProcessEngine.class.getName()).get("value");
           if (processFile == null || "".equals(processFile)) {
               throw new IllegalArgumentException("EnableProcessEngine 配置文件错误");
           }

           ClassPathXmlProcessParser xmlProcessParser = new ClassPathXmlProcessParser(processFile);
           List<ProcessModel> modelList = xmlProcessParser.parse();

           // 2. 注册ProcessContextFactory,使用spring体用的BeanDefinitionBuilder来构造
           //public ProcessContextFactory(List<ProcessModel> models,ProcessorInstanceCreator processorInstanceCreator)这个构造函数
           BeanDefinitionBuilder beanDefinitionBuilder = BeanDefinitionBuilder.rootBeanDefinition(ProcessContextFactory.class);
           beanDefinitionBuilder.addConstructorArgValue(modelList);
           // 依赖和引用spring容器里的其他bean，springBeanInstanceCreator
           beanDefinitionBuilder.addConstructorArgReference("springBeanInstanceCreator");
           registry.registerBeanDefinition(ProcessContextFactory.class.getName(),beanDefinitionBuilder.getBeanDefinition());
       }catch (Exception e){
            log.error("ProcessRegister register error {}",e.getMessage());
       }

    }
}
